const myRequest = require('../../tool/myRequest')
const tool = require('../../tool/tool')
const daoUser = require('../../dao/daoUser')
const cheerio = require('cheerio');

// 解析分类列表里面的漫画路径数据，并保存到数据库
function xxx(page) {
  myRequest('http://localhost:8422/pages/test.html', {}).then(d => {
    // myRequest('https://manwast.cc/booklist?img_host=4&page=' + page, {}).then(d => {
    if (d.status == 200) {
      const $ = cheerio.load(d.data);
      let aTags = $('.manga-list-2 .manga-list-2-title a');
      let arr = [];
      if (aTags.length == 0) { console.log(`==*****=====没有找到对应的目标====***===`,); return };
      aTags.each((num, item) => {
        // console.log(``, item.attribs.href, item.attribs.href.split('/'))
        let href_ = item.attribs.href;
        let split_ = href_.split('/');
        arr.push(`('${split_[2]}', '${href_}', 1)`);
      })
      daoUser.addBook([arr.join(',')]);
      okLength += 1;
      console.log(`page：${page}，curr：${okLength}`, d.data.substring(0, 30))
    } else console.log(`请求失败`,)
  }).catch(e => { console.log(`e`, e) })
}

// let okLength = 0;
// for (let index = 0; index < 222; index++) {
//   xxx(index)
// }


const exportsObject = {
  // 解析分类-列表里面的漫画路径数据，并保存到数据库，解析 - 新漫
  getBooksOfTypeToNewBook(obj = {}) {
    obj.url = obj.url || 'http://localhost:8422/pages/test.html'
    console.log(`加载：`, obj.url)
    return new Promise((resolve, reject) => {
      myRequest(obj.url, {}).then(d => {
        if (d.status == 200) {
          const $ = cheerio.load(d.data);
          let aTags = $('.manga-list-2 .manga-list-2-title a');
          let arr = [];
          let endBookId = '';
          if (aTags.length == 0) { console.log(`==*****=====没有找到对应的目标====***===`,); reject({}); return };
          aTags.each((num, item) => {
            // console.log(``, item.attribs.href, item.attribs.href.split('/'))
            let href_ = item.attribs.href;
            let split_ = href_.split('/');
            arr.push(`('${split_[2]}', '${href_}', 1)`);
            endBookId = String(split_[2]);
          })

          let nextPageElement = $('.pagination2 li a')
          let nextPage = 0;
          nextPageElement.each((num, item) => { if ($(item).text().trim() == '下一页') { nextPage = item.attribs['data-page']; } })

          daoUser.addBook([arr.join(',')]).then(d => {
            // console.log(`保存成功`, d)
            daoUser.getBookIsExist([endBookId]).then(ii => {
              // console.log(`ii`, ii, ii.length)
              resolve({
                status: 'ok',
                nextUrl: nextPage ? tool.jsonToUrl({ page: nextPage }, obj.url) : '',
                isExistName: ii[0].name_,
                ii: JSON.stringify(ii)
              })
            }).catch(eeee => {
              console.log(`eeee`, eeee)
            })
          }).catch(e => { console.log(`保存失败`, e); reject({}); })

          // okLength += 1;
          // console.log(`page：${page}，curr：${okLength}`, d.data.substring(0, 30))
          // console.log(`arr`, arr, endBookId, typeof endBookId, arr.length, nextPage)
        } else console.log(`请求失败`,)
      }).catch(e => { console.log(`e`, e); reject({ url: obj.url }); })
    })
  },
  getBooksOfTypeToNewBook_run() {
    function rrr(url = '', existCount = 0) {
      exportsObject.getBooksOfTypeToNewBook({ url }).then(d => {
        console.log(`d=d=`, d)
        if (d.isExistName) {
          existCount++;
        }
        if (existCount > 40) return;
        rrr(d.nextUrl, existCount);
      }).catch(e => { console.log(`e=-=-=e`, e) })
    }
    daoUser.getBase_url().then(d => {
      d.forEach(item => {
        if (item.base_url_id == 1) {
          rrr(item.base_url + '/booklist?tag=&end=&gender=-1&has_full=&area=&sort=2&level=-1&page=1', 0)
          rrr(item.base_url + '/booklist?tag=&end=&gender=-1&has_full=&area=&sort=2&level=-1&page=50', 0)
          rrr(item.base_url + '/booklist?tag=&end=&gender=-1&has_full=&area=&sort=2&level=-1&page=100', 0)
          rrr(item.base_url + '/booklist?tag=&end=&gender=-1&has_full=&area=&sort=2&level=-1&page=150', 0)
        }
      })
    })

  },

  // 解析搜索-列表里面的漫画路径数据，并保存到数据库
  getBooksOfSearch(obj = { baseUrlArr: [], tagObj: [] }) {
    obj.url = obj.url || 'http://localhost:8422/pages/test.html'
    // console.log(`obj`, obj)
    console.log(`加载：`, obj.tagObj.tag_title, obj.url)
    return new Promise((resolve, reject) => {
      myRequest(obj.url, {}).then(d => {
        if (d.status == 200) {
          const $ = cheerio.load(d.data);
          let aTags = $('ul.book-list .book-list-cover a');
          let arr = [];
          if (aTags.length == 0) { console.log(`==*****=====没有找到对应的目标====***===`,); reject({}); return };
          aTags.each((num, item) => {
            // console.log(``, item.attribs.href, item.attribs.href.split('/'))
            let href_ = item.attribs.href;
            let split_ = href_.split('/');
            arr.push(`('${split_[2]}', '${href_}', 1)`);
          })

          let nextPageElement = $('.pagination2 li a')
          let nextPage = 0;
          nextPageElement.each((num, item) => { if ($(item).text().trim() == '下一页') { nextPage = item.attribs['data-page']; } })

          daoUser.addBook([arr.join(',')]).then(d => {
            // console.log(`保存成功`, d)
            resolve({
              status: 'ok',
              nextUrl: nextPage ? tool.jsonToUrl({ page: nextPage }, obj.url) : '',
              tag: obj.tagObj
            })
            if (!nextPage) { daoUser.updateTag([obj.tagObj?.tag_id || 0]) }
          }).catch(e => { console.log(`保存失败`, e); reject({}); })

          // okLength += 1;
          // console.log(`page：${page}，curr：${okLength}`, d.data.substring(0, 30))
          // console.log(`arr`, arr, arr.length)
        } else console.log(`请求失败`,)
      }).catch(e => { console.log(`e`, e); reject({ errMsg: obj.tagObj.tag_title, url: obj.url }); })
    })
  },
  // 在有限数字内添加books
  addBooksOfNumber() {
    let arr = [];
    let index__ = 10001;
    let runCount = 5;
    setInterval(() => {
      if (runCount > 0 && index__ < 127892) {
        runCount--;
        arr = [];
        for (let index = 0; index < 100; index++) {
          arr.push(`(${index__}, '/book/${index__}', 1)`)
          index__++;
        }
        console.log(`arr`, arr)
        daoUser.addBook([arr.join(',')]).then(d => {
          console.log(`d`, d, arr.join(','))
          runCount++;
        }).catch(e => { console.log(`保存失败`, e); })
      }
    }, 50);
  }
}

module.exports = exportsObject;